package Cache;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.CacheStats;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;

import java.util.concurrent.TimeUnit;

/**
 * @leiwenkang 2018-01-18 12:07.
 */
public class LoadingCacheTest {
    private LoadingCache<String, String> cache = getUserNameMap();

    public LoadingCacheTest() {

    }

    private String name = "dungang";
    private LoadingCache<String, String> getUserNameMap(){
        /**
         * 5秒自动过期
         */
        cache = CacheBuilder.newBuilder()
                .maximumSize(1)
                .expireAfterWrite(1000, TimeUnit.SECONDS)
                .recordStats()
                .removalListener(new RemovalListener<String, String>() {
                    @Override
                    public void onRemoval(RemovalNotification<String, String> notification) {
                        //逻辑
                        System.out.println("remove: " + notification.getKey());
                    }
                })
                .build(new CacheLoader<String, String>() {
                    @Override
                    public String load(String id) throws Exception {
                        System.out.println("method inovke");
                        System.out.println("name : " + name);
                        //这里执行查询数据库，等其他复杂的逻辑
                        return "User:" + id;
                    }
                });
        return cache;
    }

    public String getUserName(String id) throws Exception {
//        System.out.println(cache.asMap());
//        CacheStats cacheStats = cache.stats();
//        System.out.println(cacheStats.hitRate());
        return cache.get(id);
    }

    public static void main(String[] args) throws Exception {
        LoadingCacheTest us = new LoadingCacheTest();
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.println(us.getUserName(String.valueOf(i)));
                TimeUnit.SECONDS.sleep(1);
            }
        }
    }
}
